<?php
//require("connection.php");
session_start();

function htmlInput($inputName, $type, $req, $readonly=false, $content=""){
	$htmlInput="<div ".($type=="date" ? "class=\"combo datebox\"" : "")." align=\"left\">";
	$htmlInput.="<input style=\"float: left;\" type=\"text\" id=\"".$inputName."\" name=\"".$inputName."\" size=\"17\" ".($req!="" ? "class=\"".$req."\"" : "")
	." ".(substr_count($type,"number")>0 ? "onkeypress=\"return onlyNumbers(event);\"" : "")." ".($readonly==true ? "readonly=\"readonly\"" : "" )." value=\"".$content."\" />";
	$htmlInput.="</div>";
	return $htmlInput;
}

function new_ot($costo){
	$sql="
	INSERT into magove_t_folios (mag_folio, mag_year, mag_costo, mag_comment, mag_currency, mag_iva, mag_pago, mag_cambio, insert_id, insert_date, active)
	VALUES('".$_POST["mag_folio"]."','".($_POST["mag_year"]!=1 ? $_POST["mag_year"] : $_POST["mag_year_alt"])."','".$costo."','".$_POST["mag_comment"]."','".$_POST["mag_currency"]."',".($_POST["mag_iva"]=="on" ? 1 : 0).", '".($_POST["mag_pago"]!='' ? deFormatDate($_POST["mag_pago"]) : '')."', '".$_POST["mag_cambio"]."',
			".$_SESSION["uid"].",'".date(Y."-".m."-".d)."',1);";
	$query=mysql_query($sql) or die("Ha ocurrido un error al crear la nueva OT:<p>".mysql_error()."<p>Your MYSQL statement:<p>".$sql);

	$sql="SELECT @@IDENTITY AS 'mag_id';";
	$id_query=mysql_query($sql) or die("Ha ocurrido un error al extraer el ID de la OT:<p>".mysql_error()."<p>Your MYSQL statement:<p>".$sql);
	$row=mysql_fetch_array($id_query);
	
	return($row["mag_id"]);
	
}

function new_cot($mag_id){
	for($x=1;$x<=$_POST["count_cot"];$x++){
		if($_POST["mag_cotizacion_valor".$x]!=""){
			$sql="
			INSERT into magove_t_cotizaciones (mag_id, mag_cotizacion_valor, mag_cotizacion, insert_id, insert_date, active)
			VALUES('".$mag_id."','".$_POST["mag_cotizacion_valor".$x]."','".$_POST["mag_cotizacion".$x]."',
			".$_SESSION["uid"].",'".date(Y."-".m."-".d)."',1);";
			$query=mysql_query($sql) or die("Ha ocurrido un error al añadir las cotizaciones:<p>".mysql_error()."<p>Your MYSQL statement:<p>".$sql);
		}
	}
}

function new_buy($mag_id){
	for($x=1;$x<=$_POST["count_buy"];$x++){
		if($_POST["mag_compra_valor".$x]!=""){
			$sql="
			INSERT into magove_t_compras (mag_id, mag_compra_valor, mag_compra, mag_mail, insert_id, insert_date, active)
			VALUES('".$mag_id."','".$_POST["mag_compra_valor".$x]."','".$_POST["mag_compra".$x]."','".$_POST["mag_mail".$x]."',
			".$_SESSION["uid"].",'".date(Y."-".m."-".d)."',1);";
			$query=mysql_query($sql) or die("Ha ocurrido un error al añadir las órdenes de compra:<p>".mysql_error()."<p>Your MYSQL statement:<p>".$sql);
		}
	}
}

function new_mag($mag_id){
	for($x=1;$x<=$_POST["count_mag"];$x++){
		if($_POST["mag_numero".$x]!=""){
			$sql="
			INSERT into magove_t_partes (mag_id, mag_cliente, mag_numero, insert_id, insert_date, active)
			VALUES('".$mag_id."','".$_POST["mag_cliente".$x]."','".$_POST["mag_numero".$x]."',
			".$_SESSION["uid"].",'".date(Y."-".m."-".d)."',1);";
			$query=mysql_query($sql) or die("Ha ocurrido un error al añadir los números MAG:<p>".mysql_error()."<p>Your MYSQL statement:<p>".$sql);
		}
	}
}

function generateInsert($fields, $table){
		$sql="INSERT into ".$table." (";
		foreach($fields as $value)
			$sql.=$value.", ";
		$lastValue=$value;
		$sql.=" insert_id, insert_date, active) VALUES(";
		foreach($_POST as $key => $value){
			$sql.="'".$value."', ";
			if($key==$lastValue)
				break;
		}
		$sql.=$_SESSION["uid"].",'".date(Y."-".m."-".d)."',1);";
		return $sql;
}

function generateUpdate($fields, $table, $key){
		$sql="UPDATE ".$table." SET ";
		foreach($fields as $value)
			$sql.=$value."='".$_POST[$value]."', ";
		$sql.=" update_id='".$_SESSION["uid"]."', update_date='".date(Y."-".m."-".d)."'";
		$sql.=" WHERE ".$key."='".$_POST[$key]."'";
		return $sql;
}

function formatDate($mysqlDate){
	return ($mysqlDate!="" && $mysqlDate!="0000-00-00" && isset($mysqlDate) ? date("d/m/Y",strtotime($mysqlDate)) : "");
}

function deFormatDate($phpDate){
  return substr($phpDate,6,4)."-".substr($phpDate,3,2)."-".substr($phpDate,0,2);
}

if($_POST["addtype"]=="labor"){
	$_POST["mag_date"]=deFormatDate($_POST["mag_date"]);
	$fields=array("mag_id", "mag_date_labor","mag_hours","mag_type_labor", "mag_part", "mag_cost_labor");
	$connection=mysql_connect($server,$username,$password);
	if($connection){
		$database=mysql_select_db($db, $connection);
		$sql="SELECT mag_labor_price
		FROM magove_t_labor_price
		WHERE mag_labor='".$_POST["mag_type_labor"]."';";
		$query=mysql_query($sql) or die("Ha ocurrido un error: ".mysql_error()."<p>Your MYSQL statement:<p>".$sql);
		$labor=mysql_fetch_array($query);
		$_POST["mag_cost_labor"]=$labor["mag_labor_price"]*$_POST["mag_hours"];
		$sql=generateInsert($fields, "magove_t_spend_labor");
		$query=mysql_query($sql) or die('{ "success": "Ha ocurrido un error: '.mysql_error().'" }');
		echo '{ "success": "y" }';
	}
}

if($_POST["addtype"]=="buy"){
	$_POST["mag_date_buy"]=deFormatDate($_POST["mag_date_buy"]);
		$fields=array("mag_id", "mag_factura", "mag_date_buy", "mag_concept_buy","mag_cost_buy");
		$sql=generateInsert($fields, "magove_t_spend_buy");
		$connection=mysql_connect($server,$username,$password);
		if($connection){
			$database=mysql_select_db($db, $connection);
			$query=mysql_query($sql) or die('{ "success": "Ha ocurrido un error: '.mysql_error().'" }');
			echo '{ "success": "y" }';
		}
}

if($_POST["addtype"]=="storage"){
	$_POST["mag_date_storage"]=deFormatDate($_POST["mag_date_storage"]);
		$fields=array("mag_id", "mag_date_storage", "mag_order_storage", "mag_concept_storage","mag_cost_storage");
		$sql=generateInsert($fields, "magove_t_spend_storage");
		$connection=mysql_connect($server,$username,$password);
		if($connection){
			$database=mysql_select_db($db, $connection);
			$query=mysql_query($sql) or die('{ "success": "Ha ocurrido un error: '.mysql_error().'" }');
			echo '{ "success": "y" }';
		}
}

if($_POST["addtype"]=="fact"){
		$_POST["mag_elaboracion"]=deFormatDate($_POST["mag_elaboracion"]);
		$fields=array("mag_id", "mag_elaboracion", "mag_num_factura", "mag_costo_factura", "mag_currency","mag_observaciones");
		$sql=generateInsert($fields, "magove_t_facturas");
		$connection=mysql_connect($server,$username,$password);
		if($connection){
			$database=mysql_select_db($db, $connection);
			$query=mysql_query($sql) or die('{ "success": "Ha ocurrido un error: '.mysql_error().'" }');
			echo '{ "success": "y" }';
		}
}

if(isset($_POST["optype"])){
	if($_POST["optype"]=="u"){
    if($_POST["fileName"]=="mag_facturas.php"){
  		$_POST["mag_elaboracion"]=deFormatDate($_POST["mag_elaboracion"]);
      $_POST["mag_fecha_pago"]=($_POST["mag_fecha_pago"]!="" ? deFormatDate($_POST["mag_fecha_pago"]) : "");
      $_POST["mag_fecha_pago_programado"]=($_POST["mag_fecha_pago_programado"]!="" ? deFormatDate($_POST["mag_fecha_pago_programado"]) : "");
      $_POST["mag_fecha_presentacion"]=($_POST["mag_fecha_presentacion"]!="" ? deFormatDate($_POST["mag_fecha_presentacion"]) : "");
      $_POST["mag_fecha_cancelacion"]=($_POST["mag_fecha_cancelacion"]!="" ? deFormatDate($_POST["mag_fecha_cancelacion"]) : "");
      $fields=array("mag_costo_factura", "mag_elaboracion", "mag_fecha_pago", "mag_fecha_pago_programado", "mag_fecha_presentacion", "mag_fecha_cancelacion", "status", "mag_observaciones");
      $sql=generateUpdate($fields, "magove_t_facturas", "mag_fact_idx");
      $connection=mysql_connect($server,$username,$password);
      if($connection){
        $database=mysql_select_db($db, $connection);
        $query=mysql_query($sql) or die('{ "success": "Ha ocurrido un error: '.mysql_error().'" }');
        echo '{ "success": "y" }';
      }
    }
    if($_POST["fileName"]=="mag_edit_spend.php"){
      $_POST["mag_date_".$_POST["mag_spend"]]=deFormatDate($_POST["mag_date_".$_POST["mag_spend"]]);
      $fields=array("mag_date_".$_POST["mag_spend"]);
      switch($_POST["mag_spend"]){
        case "labor":
          $fields[]="mag_hours";
          $fields[]="mag_type_labor";
          $fields[]="mag_part";
          $fields[]="mag_cost_labor";
          break;
        case "buy":
          $fields[]="mag_factura";
          break;
        case "storage":
          $fields[]="mag_order_storage";
          break;
      }
      if($_POST["mag_spend"]=="buy" || $_POST["mag_spend"]=="storage"){
        $fields[]="mag_concept_".$_POST["mag_spend"];
        $fields[]="mag_cost_".$_POST["mag_spend"];
      }
      $connection=mysql_connect($server,$username,$password);
      if($connection){
        $database=mysql_select_db($db, $connection);
        $sql="SELECT mag_labor_price
        FROM magove_t_labor_price
        WHERE mag_labor='".$_POST["mag_type_labor"]."';";
        $query=mysql_query($sql) or die('{ "success": "Ha ocurrido un error: '.mysql_error().'" }');
        $labor=mysql_fetch_array($query);
        $_POST["mag_cost_labor"]=$labor["mag_labor_price"]*$_POST["mag_hours"];
        $sql=generateUpdate($fields, "magove_t_spend_".$_POST["mag_spend"], "sid");
        $query=mysql_query($sql) or die('{ "success": "Ha ocurrido un error: '.mysql_error().'" }');
        echo '{ "success": "y" }';
      }
    }
  }
}
?>